// console.log(window.location.href);
// const param = window.location.href.match(/\?([^&]*([=][^&]*)?&)*id=([^&]*)&?/);
// console.log(param);
// if (!param) {
//   alert("文章不存在");
//   window.location.href = "/index.html";
// }

const requestParams = HTTP.getRequestParams();
export const articleID = parseInt(requestParams["id"]);
if (isNaN(articleID)) {
  alert("文章不存在");
  window.location.href = "/index.html";
}

// AutoAnimate
import autoAnimate from "/js/third/auto-animate.min.js";
(async function () {
  /**
   * 目录条目类，用于管理和操作目录结构
   */
  class CatalogItem {
    constructor(id, depth, prefix, value) {
      this.id = id;
      this.depth = depth;
      this.prefix = prefix;
      this.value = value;
      this.children = [];
    }

    size() {
      let size = this.children.length;
      for (const child of this.children) {
        size += child.size();
      }
      return size;
    }

    /**
     * 添加子目录条目
     * @param {string} id ID
     * @param {number} depth 目录深度
     * @param {string} prefix 前缀
     * @param {string} value 目录值
     */
    addChild(id, depth, prefix, value) {
      if (this.depth >= depth) return null;

      const item = new CatalogItem(id, depth, prefix, value);
      for (const child of this.children) {
        const addedItem = child.addChild(item);
        if (addedItem) {
          return addedItem;
        }
      }
      this.children.push(item);
      return item;
    }

    addChild(item) {
      if (this.depth >= item.depth) return null;
      for (const child of this.children) {
        const addedItem = child.addChild(item);
        if (addedItem) {
          return addedItem;
        }
      }
      this.children.push(item);
      return item;
    }
  }

  /**
   * 目录管理器，用于操作和维护目录列表
   */
  class CatalogManager {
    constructor() {
      this.catalogCount = 0;
      this.catalogList = [];
      this.listElement = document.createElement("ul");
      this.listElement.style.display = "flex";
      this.listElement.style.flexDirection = "column";
      this.listElement.style.listStyle = "none";
      this.listElement.style.marginTop = "0.5em";
    }

    size() {
      let size = 0;
      for (const item of this.catalogList) {
        size += item.size();
      }
      return size;
    }

    /**
     * 添加目录条目
     * @param {number} depth 目录深度（原始深度，未减1）
     * @param {string} value 目录值
     * @param {string} prefix 前缀
     */
    addCatalogItem(depth, value, prefix = "") {
      // 校验输入
      if (typeof depth !== "number" || typeof value !== "string") {
        console.error("错误：无效的目录条目参数。");
        return;
      }

      const catalogItem = new CatalogItem(
        `catalog-item-${++this.catalogCount}`,
        depth,
        prefix,
        value,
      );
      if (this.catalogList.length === 0) {
        // 如果目录列表为空，直接添加
        this.catalogList.push(catalogItem);
      } else {
        const lastItem = this.catalogList[this.catalogList.length - 1];
        if (lastItem.depth < depth) {
          // 如果新目录项的深度大于当前最深的目录项，则添加为子目录
          if (!lastItem.addChild(catalogItem))
            this.catalogList.push(catalogItem);
        } else {
          // 否则直接添加到目录列表
          this.catalogList.push(catalogItem);
        }
      }

      return catalogItem;
    }

    /**
     * 渲染目录列表
     */
    renderCatalogList(containerElement) {
      console.log("开始渲染目录列表");
      function renderChildrenList(item) {
        const childList = document.createElement("ul");
        for (const child of item.children) {
          const childListItem = document.createElement("li");
          const a = document.createElement("a");
          a.href = `#${child.id}`;
          a.textContent = `${child.prefix}${child.value}`;
          childListItem.appendChild(a);
          childListItem.appendChild(renderChildrenList(child));
          childList.appendChild(childListItem);
        }
        return childList;
      }

      this.listElement.innerHTML = "";
      for (const catalogItem of this.catalogList) {
        const listItem = document.createElement("li");
        const a = document.createElement("a");
        a.href = `#${catalogItem.id}`;

        // 设置目录条目文本
        const prefixSpan = document.createElement("span");
        prefixSpan.textContent = catalogItem.prefix;
        a.appendChild(prefixSpan);

        const valueSpan = document.createElement("span");
        valueSpan.textContent = catalogItem.value;
        a.appendChild(valueSpan);

        listItem.appendChild(a);

        // 递归渲染子目录
        if (catalogItem.children.length !== 0) {
          const childrenList = renderChildrenList(catalogItem);
          listItem.appendChild(childrenList);
        }

        this.listElement.appendChild(listItem);
      }

      // 将目录列表插入到DOM中
      containerElement.appendChild(this.listElement);
    }
  }

  let configuration = {};
  await Promise.all([WebsiteConfigurationPromise]).then((arr) => {
    configuration = arr[0];
  });

  const imgLoadingSrc = "/images/image.loading.png";
  const imgErrorSrc = "/images/image.error.png";

  // 隐藏内容
  document.body.style.display = "none";

  const articleResult = await HTTP.request(
    {
      method: "get",
      url: "/api/article/" + articleID,
    },
    false,
  );

  if (!articleResult || articleResult.type === "failure") {
    // window.location.href = "./message.html?message=文章不存在";
    // return;
    alert("文章不存在");
    window.location.href = "/index.html";
  }

  const article = articleResult.data;
  if (!article) {
    alert("文章加载失败！");
    window.location.href = "/index.html";
  }

  // 修改页面信息
  document.title = article.sort_name + "——" + article.title;
  const description = `${configuration.websiteName}——文章——${article.author}——${document.title}`;
  document.querySelector("meta[name='description']").content = description;

  document.querySelector("meta[property='og:title']").content = document.title;
  document.querySelector("meta[property='og:url']").content =
    `http://cyue.net/pages/article.html?id=${article.id}`;
  document.querySelector("meta[property='og:description']").content =
    description;

  document.querySelector("meta[name='twitter:title']").content = document.title;
  document.querySelector("meta[name='twitter:description']").content =
    description;
  document.querySelector("meta[name='twitter:creator']").content =
    `@${article.publisher}`;

  document.getElementsByClassName("article-title")[0].textContent =
    article.title;
  document.getElementsByClassName("article-date")[0].textContent = article.date;

  // 原作者
  const authorElement = document.getElementsByClassName("article-author")[0];
  authorElement.textContent = article.author;
  authorElement.setAttribute("target", "_blank");
  if (article.author_home_page) {
    authorElement.href = article.author_home_page;
  }

  if (article.publisher === article.author) {
    authorElement.href = `/pages/author.html?id=${article.publisher_id}`;
  } else {
    const div = document.createElement("div");
    div.className = "article-publisher-container";
    div.innerHTML = `
      <span>发布者：</span>
      <a class="article-publisher" href="/pages/author.html?id=${article.publisher_id}" target="_blank">${article.publisher}</a>
  `;
    document.getElementsByClassName("article-author-container")[0].after(div);
  }

  const articleElement = document.getElementsByTagName("article")[0];

  let articleContentData = article.contentData;
  if (Array.isArray(articleContentData)) {
    articleContentData = {
      type: "json",
      version: "v1",
      content: articleContentData,
    };
  }

  // json v1
  if (
    articleContentData.type === "json" &&
    (articleContentData.version === "v1" ||
      articleContentData.jsonVersion === "v1") &&
    Array.isArray(articleContentData.content)
  ) {
    // console.log("json v1");
    for (let index = 0; index < articleContentData.content.length; index++) {
      const node = articleContentData.content[index];

      // 副标题
      if (node.type === "subtitle") {
        const h2 = document.createElement("h2");
        h2.textContent = typeof node.value === "string" ? node.value : "";
        articleElement.appendChild(h2);
      }
      // 段落
      else if (node.type === "paragraph") {
        const p = document.createElement("p");

        // 遍历并处理段落中的子节点
        const 遍历段落子节点 = function (parent, childNode) {
          // 替换字符串中的尖括号
          if (typeof childNode.value === "string") {
            childNode.value = childNode.value
              .replaceAll("<", "&lt;")
              .replaceAll(">", "&gt;");
          }
          if (childNode.type === "text" || childNode.type === "#text") {
            parent.innerHTML += childNode.value;
            return;
          }

          // 老版本 和 date, time
          // 处理单个节点
          if (!Array.isArray(childNode.value)) {
            parent.innerHTML += `<${childNode.type}>${childNode.value}</${childNode.type}>`;
          }
          // 新版本, node.value 为 数组
          // 处理包含多个子节点的情况
          else {
            // 创建子节点，并遍历子节点内容，再加回父节点
            const childElement = document.createElement(childNode.type);
            for (let index = 0; index < childNode.value.length; index++) {
              const n = childNode.value[index];
              遍历段落子节点(childElement, n);
            }
            parent.appendChild(childElement);
          }
        };

        const childCount = Array.isArray(node.value) ? node.value.length : 0;
        for (let j = 0; j < childCount; j++) {
          const child = node.value[j];
          遍历段落子节点(p, child);
        }
        articleElement.appendChild(p);
      }
      // 图片
      else if (node.type === "figure") {
        const figure = document.createElement("figure");
        figure.className = "article-figure";

        const [img, figcaption] = Array.isArray(node.value) ? node.value : [];
        if (img) {
          const imgSrc = typeof img.value === "string" ? img.value : "";
          const imgElement = document.createElement("img");
          imgElement.decoding = "async";
          imgElement.loading = "lazy";
          imgElement.dataset.src = imgSrc;
          imgElement.src = imgSrc; // 占位图src
          imgElement.onload = function () {
            if (imgElement.src !== imgSrc) imgElement.src = imgSrc; // 实际图src
            imgElement.onload = null;
          };
          imgElement.onerror = function () {
            imgElement.src = imgErrorSrc; // 图片加载失败的备选图
          };
          figure.appendChild(imgElement);
        }
        if (figcaption) {
          const figcaptionElement = document.createElement("figcaption");
          figcaptionElement.textContent =
            typeof figcaption.value === "string" ? figcaption.value : "";
          figure.appendChild(figcaptionElement);
        }
        articleElement.appendChild(figure);
      }
      // 其他
      else {
        const valueString = typeof node.value === "string" ? node.value : "";
        const unknownElement = document.createElement(node.type);
        // 图片
        if (node.type === "img") {
          unknownElement.setAttribute("src", valueString);
          if (node.alt) unknownElement.setAttribute("alt", node.alt);
        }
        // 不是图片
        else {
          unknownElement.textContent = valueString;
        }
        articleElement.appendChild(unknownElement);
      }
    }
  }
  // json v2
  else if (
    articleContentData.type === "json" &&
    (articleContentData.version === "v2" ||
      articleContentData.jsonVersion === "v2") &&
    Array.isArray(articleContentData.content)
  ) {
    // console.log("json v2");
    for (let index = 0; index < articleContentData.content.length; index++) {
      const node = articleContentData.content[index];

      // 段落
      if (node.type === "paragraph" || node.tagName === "p") {
        const p = document.createElement(node.tagName);

        // 遍历并处理段落中的子节点
        const 遍历段落子节点 = function (parent, childNode) {
          // 替换字符串中的尖括号
          if (childNode.textContent) {
            childNode.textContent = childNode.textContent
              .replaceAll("<", "&lt;")
              .replaceAll(">", "&gt;");
          }

          // 普通文本节点
          if (childNode.type === "text" || childNode.type === "#text") {
            parent.innerHTML += childNode.textContent;
            return; // 结束
          }

          // 子节点处理
          if (!childNode.children) return;
          // 处理单个节点
          if (childNode.children.length === 0) {
            parent.innerHTML += `<${childNode.tagName}>${childNode.textContent}</${childNode.tagName}>`;
          }
          // 处理包含多个子节点的情况
          else {
            // 创建子节点，并遍历子节点内容，再加回父节点
            const childElement = document.createElement(childNode.tagName);
            for (let index = 0; index < childNode.children.length; index++) {
              const n = childNode.children[index];
              遍历段落子节点(childElement, n);
            }
            parent.appendChild(childElement);
          }
        };

        for (let j = 0; j < (node.children ? node.children.length : 0); j++) {
          const childNode = node.children[j];
          遍历段落子节点(p, childNode);
        }
        articleElement.appendChild(p);
      }
      // 图片
      else if (node.type === "figure") {
        const figure = document.createElement(node.tagName);
        figure.className = "article-figure";

        const [img, figcaption] = node.children;
        if (img) {
          const imgElement = document.createElement("img");
          imgElement.decoding = "async";
          imgElement.loading = "lazy";
          imgElement.dataset.src = img.src;
          imgElement.src = imgLoadingSrc; // 占位图src
          imgElement.onload = function () {
            if (imgElement.src !== img.src) {
              imgElement.src = img.src; // 实际图src
            }
            imgElement.onload = null;
          };
          imgElement.onerror = function () {
            imgElement.src = imgErrorSrc; // 图片加载失败的备选图
          };
          figure.appendChild(imgElement);
        }
        if (figcaption) {
          const figcaptionElement = document.createElement("figcaption");
          figcaptionElement.textContent = figcaption.textContent;
          figure.appendChild(figcaptionElement);
        }
        articleElement.appendChild(figure);
      }
      // 其他
      else {
        const unknownElement = document.createElement(node.tagName);
        unknownElement.textContent = node.textContent;
        unknownElement.setAttribute("href", node.href);
        unknownElement.setAttribute("src", node.src);
        unknownElement.setAttribute("alt", node.alt);
        articleElement.appendChild(unknownElement);
      }
    }
  }
  // markdown
  else if (articleContentData.type === "markdown") {
    console.log("markdown");
    try {
      articleElement.innerHTML += marked.parse(articleContentData.content);
    } catch (e) {
      console.error(e);

      const markedScript = document.createElement("script");
      markedScript.src = "/js/third/marked.min.js";
      document.body.appendChild(markedScript);
      await new Promise((resolve) => {
        markedScript.onload = function () {
          resolve();
        };
      });
      articleElement.innerHTML += marked.parse(articleContentData.content);
      setTimeout(() => {
        articleElement.querySelectorAll("img").forEach((item) => {
          item.decoding = "async";
          item.loading = "lazy";
        });
      }, 0);
    }
  }
  // html
  else if (articleContentData.type === "html") {
    articleElement.innerHTML += articleContentData.content;
  }

  // 修改链接标签
  articleElement.querySelectorAll("a").forEach((e) => {
    e.setAttribute("target", "_blank");
  });

  // 高亮代码块
  const codeElements = articleElement.getElementsByTagName("code");
  if (codeElements && codeElements.length !== 0) {
    /**
     * <!-- highlight -->
     * <link rel="stylesheet" href="/css/third/highlight.min.css">
     * <script src="/js/third/highlight.min.js"></script>
     */
    (function () {
      const css = document.createElement("link");
      css.rel = "stylesheet";
      css.href = "/css/third/highlight.min.css";
      document.head.appendChild(css);
    })();
    await new Promise((resolve) => {
      const script = document.createElement("script");
      script.src = "/js/third/highlight.min.js";
      document.head.appendChild(script);
      script.onload = function () {
        resolve();
      };
    });
    hljs.highlightAll();
  }

  // 浏览量
  // HTTP.request({
  //   method: "GET",
  //   url: `/api/article/view/${article.id}`,
  // }).then((response) => {
  //   const result = response.data;
  //   if (result.type === "success") {
  //     article.view = result.data;
  //     const articleViewCountElement = document.getElementById(
  //       "article-info-view-count",
  //     );
  //     if (articleViewCountElement) {
  //       articleViewCountElement.textContent = article.view;
  //     }
  //   }
  // });
  const articleViewCountElement = document.getElementById(
    "article-info-view-count",
  );
  if (articleViewCountElement) {
    articleViewCountElement.textContent = article.view;
  }

  // article-info-block 动画
  const articleInfoBlockElement = document.getElementById("article-info-block");
  autoAnimate(articleInfoBlockElement);

  // 文章分类
  const articleSortElement = document.getElementById("article-info-sort");
  articleSortElement.innerHTML += `<a href="/pages/sort.html#${article.sort_name}" target="_blank">${article.sort_name}</a>`;

  // 文章合集
  let articleSetIDs = [];
  HTTP.request({
    method: "GET",
    url: `/api/article/set/article/${article.id}`,
  }).then(async (response) => {
    const result = response.data;
    if (result.type === "success") {
      articleSetIDs = result.data;
      if (articleSetIDs.length === 0) return;

      const setElement = document.getElementById("article-info-set");
      setElement.style.display = "flex";

      for (const id of articleSetIDs) {
        const set = (
          await HTTP.request({
            method: "GET",
            url: `/api/article/set/${id}`,
          })
        ).data.data;
        const a = document.createElement("a");
        a.href = `#set-${set.name}`;
        a.textContent = set.name;
        setElement.appendChild(a);
      }
    }
  });

  // 文章标签
  HTTP.request({
    method: "GET",
    url: `/api/article/tag/article/${article.id}`,
  }).then(async (response) => {
    const result = response.data;
    if (result.type === "success") {
      const tagIDs = result.data;
      if (tagIDs.length === 0) return;

      const tagElement = document.getElementById("article-info-tag");
      tagElement.style.display = "flex";

      for (const id of tagIDs) {
        const tag = (
          await HTTP.request({
            method: "GET",
            url: `/api/article/tag/${id}`,
          })
        ).data.data;
        // console.log(tag);
        const a = document.createElement("a");
        a.href = `#tag-${tag.name}`;
        a.textContent = tag.name;
        tagElement.appendChild(a);
      }
    }
  });

  // 显示内容
  document.body.style.display = "";
  document.body.animate(
    [
      {
        opacity: 0,
      },
      {
        opacity: 1,
      },
    ],
    500,
  );

  let isSidebarInit = false;
  async function initSidebar() {
    if (isSidebarInit) return;
    else isSidebarInit = true;

    // 获取文章其他信息
    const sidebarElement = document.getElementById("sidebar"); // 侧边栏
    autoAnimate(sidebarElement);

    // 读取文章内容，创建文章目录
    const elements = articleElement.children;
    const catalogManager = new CatalogManager();
    for (const e of elements) {
      // h1
      if (e.tagName === "H1") {
        const item = catalogManager.addCatalogItem(1, e.textContent);
        e.id = item.id;
      }
      // h2
      else if (e.tagName === "H2") {
        const item = catalogManager.addCatalogItem(2, e.textContent);
        e.id = item.id;
      }
      // h3
      else if (e.tagName === "H3") {
        const item = catalogManager.addCatalogItem(3, e.textContent);
        e.id = item.id;
      }
      // h4
      else if (e.tagName === "H4") {
        const item = catalogManager.addCatalogItem(4, e.textContent);
        e.id = item.id;
      }
      // h5
      else if (e.tagName === "H5") {
        const item = catalogManager.addCatalogItem(5, e.textContent);
        e.id = item.id;
      }
      // h6
      else if (e.tagName === "H6") {
        const item = catalogManager.addCatalogItem(6, e.textContent);
        e.id = item.id;
      }
      // 图片
      else if (e.tagName === "IMG") {
        if (!e.alt) continue;
        e.id = catalogManager.addCatalogItem(2, e.alt, "[图片]").id;
      }
      // p 内的图片
      else if (e.tagName === "P") {
        const images = e.getElementsByTagName("IMG");
        if (images.length === 0) {
          continue;
        }
        for (const ie of images) {
          const item = catalogManager.addCatalogItem(2, ie.alt, "[图片]");
          ie.id = item.id;
        }
      }
      // figure 图片
      else if (e.tagName === "FIGURE") {
        const figcaption = e.getElementsByTagName("FIGCAPTION")[0];
        const item = catalogManager.addCatalogItem(
          2,
          figcaption ? figcaption.textContent : "",
          "[图片]",
        );
        e.id = item.id;
      }
    }
    // console.log(catalogManager.catalogList);
    // 渲染目录
    const catalogContainerElement = document.getElementById("catalog");
    catalogManager.renderCatalogList(catalogContainerElement);
    if (catalogManager.size() > 0) {
      catalogContainerElement.style.display = "flex";
    }

    // 分类侧边栏
    HTTP.request({
      method: "GET",
      url: `/api/article/sort/${article.sort_id}/page/1`,
    }).then((response) => {
      const infoArray = response.data.data;
      if (infoArray.length === 0) {
        return;
      }
      // 分类面板
      const div = document.createElement("div");
      const h3 = document.createElement("h3");
      const ul = document.createElement("ul");
      div.className = "panel flex-column";
      ul.className = "box-aside-list";
      h3.textContent = `更多“${article.sort_name}”文章`;
      div.appendChild(h3);
      div.appendChild(ul);

      for (const info of infoArray) {
        // 跳过当前文章
        if (info.id === article.id) {
          continue;
        }
        const li = document.createElement("li");
        li.innerHTML = `
          <a href="/pages/article.html?id=${info.id}" target="_blank">${info.title}</a>
        `;
        ul.appendChild(li);
      }

      // 添加分类面板
      if (ul.children.length !== 0) {
        sidebarElement.appendChild(div);
      }
    });

    // 合集侧边栏
    for (const id of articleSetIDs) {
      const setResult = await HTTP.request(
        {
          method: "GET",
          url: `/api/article/set/${id}/article/ids`,
        },
        false,
      );
      if (setResult.type === "success") {
        const articleIDs = setResult.data;
        // 创建合集面板
        const div = document.createElement("div");
        const h3 = document.createElement("h3");
        const ul = document.createElement("ul");
        div.className = "panel flex-column";
        ul.className = "box-aside-list";
        h3.textContent = `合集——${set.name}`;
        div.appendChild(h3);
        div.appendChild(ul);

        for (const articleID of articleIDs) {
          const article = (
            await HTTP.request({
              method: "GET",
              url: `/api/article/information/${articleID}`,
            })
          ).data.data;
          const li = document.createElement("li");
          li.innerHTML = `
            <a href="/pages/article.html?id=${article.id}">${article.title}</a>
          `;
          ul.appendChild(li);
        }

        // 添加合集面板
        if (ul.children.length !== 0) {
          sidebarElement.appendChild(div);
        }
      }
    }
  }

  // 判断屏幕大小
  if (window.innerWidth < 1024) {
    window.addEventListener("resize", () => {
      if (window.innerWidth >= 1024) {
        initSidebar();
      }
    });
  } else {
    initSidebar();
  }
})();
